package cloud.keveri.gateway.core.chain;

import cloud.keveri.gateway.plugin.api.KeveriPlugin;
import cloud.keveri.gateway.plugin.api.KeveriPluginChain;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 默认插件链实现
 * <p>
 * 作者：沈自在
 **/
public class DefaultKeveriPluginChain implements KeveriPluginChain {

    /**
     * 索引
     */
    private int index;

    /**
     * 插件列表
     */
    private final List<KeveriPlugin> plugins;

    public DefaultKeveriPluginChain(List<KeveriPlugin> plugins) {
        this.plugins = plugins;
    }

    /**
     * 插件链执行
     */
    @Override
    public Mono<Void> execute(ServerWebExchange exchange) {
        return Mono.defer(() -> {
            if (this.index < plugins.size()) {
                KeveriPlugin plugin = plugins.get(this.index++);
                boolean isSkip = plugin.skip(exchange);
                if (isSkip) {
                    return this.execute(exchange);
                }
                return plugin.process(exchange, this);
            }
            return Mono.empty();
        });
    }
}
